/*
 * @Author: wangwei wwdqq7@qq.com
 * @Date: 2025-04-01 15:00:00
 * @LastEditors: wangwei wwdqq7@qq.com
 * @LastEditTime: 2025-04-01 22:40:36
 * @FilePath: /FullStack/pro/typeorm-mysql/src/auth/strategies/jwt.strategy.ts
 * @Description: JWT策略，用于验证JWT令牌
 */
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

import { UserService } from '@/user/user.service';

/**
 * 验证JWT令牌中的负载
 * @param payload JWT令牌负载
 * @returns 验证通过的用户信息
 * @throws UnauthorizedException 如果用户不存在
 */
interface JwtPayload {
  sub: number;
  username: string;
}

interface User {
  id: number;
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private userService: UserService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: 'secretKey', // 在生产环境中应该使用环境变量
    });
  }

  async validate(payload: JwtPayload) {
    try {
      // 从数据库中查找用户，确保用户存在
      const users = await this.userService.getUsers();
      const user = users.find((user: User) => user.id === payload.sub);

      if (!user) {
        throw new UnauthorizedException('用户不存在或已被删除');
      }

      return { userId: payload.sub, username: payload.username };
    } catch (error) {
      throw new UnauthorizedException('Token验证失败：' + error.message);
    }
  }
}
